package co.yixiang.yshop.module.mp.controller.admin.customerservice;

import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.io.FileUtil;
import co.yixiang.yshop.framework.common.exception.ErrorCode;
import co.yixiang.yshop.framework.common.pojo.CommonResult;
import co.yixiang.yshop.framework.common.pojo.PageParam;
import co.yixiang.yshop.framework.common.pojo.PageResult;
import co.yixiang.yshop.module.infra.api.file.FileApi;
import co.yixiang.yshop.module.mp.controller.admin.customerservice.vo.*;
import co.yixiang.yshop.module.mp.framework.cp.config.WxCpConfiguration;
import co.yixiang.yshop.module.mp.service.customerservice.CustomerServiceService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpDepartmentService;
import me.chanjar.weixin.cp.api.WxCpKfService;
import me.chanjar.weixin.cp.api.WxCpMediaService;
import me.chanjar.weixin.cp.api.WxCpUserService;
import me.chanjar.weixin.cp.bean.WxCpDepart;
import me.chanjar.weixin.cp.bean.WxCpUser;
import me.chanjar.weixin.cp.bean.kf.WxCpKfAccountAddResp;
import me.chanjar.weixin.cp.bean.kf.WxCpKfAccountDel;
import me.chanjar.weixin.cp.bean.kf.WxCpKfServicerListResp;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static co.yixiang.yshop.framework.common.exception.util.ServiceExceptionUtil.exception;

/**
 * @author pepis
 * @apiNote
 **/
@Tag(name = "管理后台 - 客服管理")
@RestController
@RequestMapping("/cp/kf")
@Validated
@Slf4j
public class CustomerServiceController {
    @Resource
    private CustomerServiceService customerServiceService;
    @Resource
    private FileApi fileApi;

    @SneakyThrows
    @GetMapping("page")
    @Operation(summary = "获取客服列表")
    public CommonResult<PageResult<CustomerServiceVO>> getAll(PageParam pageParam) {
        PageResult<CustomerServiceVO> pageResult = customerServiceService.page(pageParam);
        return CommonResult.success(pageResult);
    }

    @SneakyThrows
    @PostMapping
    @Operation(summary = "新增客服")
    public CommonResult<WxCpKfAccountAddResp> save(@RequestBody WxCpKfAccountAddDTO add) {
        WxCpKfAccountAddResp wxCpKfAccountAddResp = customerServiceService.save(add);
        return CommonResult.success(wxCpKfAccountAddResp);
    }

    @SneakyThrows
    @PutMapping
    @Operation(summary = "编辑客服")
    public CommonResult<Boolean> update(@RequestBody WxCpKfAccountUpdDTO upd) {
        customerServiceService.update(upd);
        return CommonResult.success(true);
    }

    @SneakyThrows
    @DeleteMapping
    @Operation(summary = "删除客服")
    public CommonResult<Boolean> delete(@RequestBody WxCpKfAccountDel del) {
        customerServiceService.delete(del);
        return CommonResult.success(true);
    }

    @SneakyThrows
    @GetMapping("listServicer")
    @Operation(summary = "客服接待人")
    public CommonResult<List<ServicerVO>> listServicer(String openKfid) {
        WxCpKfService kfService = WxCpConfiguration.getCpService().getKfService();
        WxCpUserService userService = WxCpConfiguration.getCpService().getUserService();

        WxCpKfServicerListResp resp = kfService.listServicer(openKfid);
        List<ServicerVO> list = resp.getServicerList().stream().map(item -> {
            ServicerVO servicerVO = new ServicerVO();
            servicerVO.setUserId(item.getUserId());
            servicerVO.setStatus(item.getStatus());
            //获取用户
            try {
                WxCpUser user = userService.getById(item.getUserId());
                servicerVO.setName(user.getName());
            } catch (WxErrorException e) {
                log.error("获取接待人信息失败:{}", e.getMessage());
                throw exception(new ErrorCode(20250302,"获取接待人信息失败,请联系管理员"));
            }
            return servicerVO;
        }).collect(Collectors.toList());
        return CommonResult.success(list);
    }

    @SneakyThrows
    @PostMapping("addServicer")
    @Operation(summary = "保存接待人")
    public CommonResult<Boolean> addServicer(@RequestBody AddServicerDTO dto) {
        WxCpKfService kfService = WxCpConfiguration.getCpService().getKfService();
        try {
            kfService.addServicer(dto.getOpenKfid(), dto.getUserIdList());
        } catch (WxErrorException e) {
            log.error("保存接待人:{}", e.getMessage());
            throw exception(new ErrorCode(202503021,"保存接待人失败,请联系管理员"));
        }
        kfService.addServicer(dto.getOpenKfid(), dto.getUserIdList());
        return CommonResult.success(true);
    }

    @SneakyThrows
    @DeleteMapping("delServicer")
    @Operation(summary = "删除接待人")
    public CommonResult<Boolean> delServicer(@RequestBody AddServicerDTO dto) {
        WxCpKfService kfService = WxCpConfiguration.getCpService().getKfService();
        kfService.delServicer(dto.getOpenKfid(), dto.getUserIdList());
        return CommonResult.success(true);
    }

    @SneakyThrows
    @GetMapping("departmentList")
    @Operation(summary = "部门列表")
    public CommonResult<List<WxCpDepart>> departmentList() {
        WxCpDepartmentService departmentService = WxCpConfiguration.getCpService().getDepartmentService();
        List<WxCpDepart> list = departmentService.list(null);
        return CommonResult.success(list);
    }

    @SneakyThrows
    @GetMapping("listUser")
    @Operation(summary = "查询部门下用户")
    public CommonResult<List<WxCpUser>> listUser(Long departId) {
        if(departId == null){
            return CommonResult.success(new ArrayList<>());
        }
        WxCpUserService userService = WxCpConfiguration.getCpService().getUserService();
        List<WxCpUser> wxCpUsers = userService.listByDepartment(departId, true, 0);
        return CommonResult.success(wxCpUsers);
    }

    @SneakyThrows
    @PostMapping("uploadMaterial")
    @Operation(summary = "上传素材")
    public CommonResult<WxMediaUploadResult> uploadMaterial(@RequestParam(value = "file") MultipartFile file) {
        WxCpMediaService mediaService = WxCpConfiguration.getCpService().getMediaService();
        WxMediaUploadResult upload = mediaService.upload(WxConsts.MediaFileType.IMAGE, file.getOriginalFilename(), file.getInputStream());
        //获取url
        File download = mediaService.download(upload.getMediaId());
        String url = uploadFile(upload.getMediaId(), download);
        upload.setUrl(url);
        return CommonResult.success(upload);
    }

    private String uploadFile(String mediaId, File file) {
        String path = mediaId + "." + FileTypeUtil.getType(file);
        return fileApi.createFile(path, FileUtil.readBytes(file));
    }

}
